package com.hefan.api.controller.oms;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.cat.common.constant.RedisKeyConstant;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.tiger.service.JedisService;
import com.cat.tiger.util.CollectionUtils;
import com.cat.tiger.util.GlobalConstants;
import com.google.common.collect.Maps;
import com.hefan.api.service.UserLocalService;
import com.hefan.api.service.oms.RedPacketLocalService;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.bean.Message;
import com.hefan.common.ons.service.ONSProducer;
import com.hefan.common.util.DynamicProperties;
import com.hefan.common.util.HttpUtils;
import com.hefan.common.util.MapUtils;
import com.hefan.oms.bean.*;
import com.hefan.oms.itf.PresentService;
import com.hefan.oms.itf.RedPacketService;
import com.hefan.user.bean.WebUser;
import com.hefan.user.itf.WebUserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Created by hbchen on 2016/10/12.
 */
@Controller
@RequestMapping("v1/pay")
public class RedPackController {

  @Reference
  private ONSProducer onsProducer;
  @Resource
  private UserLocalService userLocalService;
  @Reference
  private WebUserService webUserService;
  @Resource
  private RedPacketLocalService redPacketLocalService;
  @Resource
  private JedisService jedisService;
  @Reference
  private PresentService presentService;
  @Reference
  private RedPacketService redPacketService;

  private Logger logger = LoggerFactory.getLogger(RedPackController.class);

  @RequestMapping(value = "/pushRedPacket", method = RequestMethod.GET)
  @ResponseBody
  public ResultBean pushRedPacket(HttpServletRequest request) {

    Map m = HttpUtils.initParam(request, Map.class);

    String userId = "";
    String liveUuid = "";
    String roomId = "";
    long presentId = 0;
    String zhuboId = "";

    if (!CollectionUtils.isEmpty(m)) {
      userId = MapUtils.getStrValue(m, "userId", "");
      liveUuid = MapUtils.getStrValue(m, "liveUuid", "");
      roomId = MapUtils.getStrValue(m, "roomId", "");
      presentId = MapUtils.getLongValue(m, "presentId", 0);
      zhuboId = MapUtils.getStrValue(m, "zhuboId", "");
    } else {
      return new ResultBean(ResultCode.ParamException.get_code(), "参数验证错误");
    }

    if (StringUtils.isBlank(userId))
      return new ResultBean(ResultCode.ParamException.get_code(), "userId验证错误");
    if (StringUtils.isBlank(liveUuid))
      return new ResultBean(ResultCode.ParamException.get_code(), "liveUuid验证错误");
    if (StringUtils.isBlank(roomId))
      return new ResultBean(ResultCode.ParamException.get_code(), "roomId验证错误");
    if (presentId <= 0)
      return new ResultBean(ResultCode.ParamException.get_code(), "presentId验证错误");
    if (StringUtils.isBlank(zhuboId))
      return new ResultBean(ResultCode.ParamException.get_code(), "zhuboId验证错误");

    //查礼物信息
    try {
      Present present = presentService.getPresentById(presentId);
      if (null == present) {
        return new ResultBean(ResultCode.UNSUCCESS.get_code(), "礼物信息获取失败");
      }

      if (present.getType() != GlobalConstants.PRESENT_TYPE_RED) {
        return new ResultBean(ResultCode.UNSUCCESS.get_code(), "礼物类型错误，应为红包");
      }
      //查红包信息
      if (present.getRedPacketId() > 0) {
        RedPacket redPacket = redPacketLocalService.selectRedPackInfo(present.getRedPacketId());
        if (redPacket == null) {
          return new ResultBean(ResultCode.UNSUCCESS.get_code(), "红包基础信息有误");
        }

        long balance = 0;
        //扣费，校验余额是否充足
        WebUser webUser = userLocalService.getWebUserByUserId(userId);
        if (webUser != null && webUser.getBalance() >= present.getPrice()) {
          balance = webUser.getBalance();//记录扣费前余额
          if (webUser.getUserType() == GlobalConstants.USER_TYPE_FLASE) {
            return new ResultBean(ResultCode.UNSUCCESS.get_code(), "虚拟币用户无法发红包");
          }
          userLocalService.incrWebUserBalance(userId, -1 * present.getPrice());
        } else {
          return new ResultBean(ResultCode.UNSUCCESS.get_code(), "余额不足");
        }



        RedPacketVo redPacketVo = new RedPacketVo();
        redPacketVo.setRedPacketId(redPacket.getId());
        redPacketVo.setLiveUuid(liveUuid);
        redPacketVo.setUserId(userId);
        redPacketVo.setFanpiaoNum(redPacket.getAmount());
        redPacketVo.setPresentFanpiao(present.getPrice());
        redPacketVo.setPersonNum(redPacket.getNumber());
        redPacketVo.setPresentName(present.getPresentName());
        redPacketVo.setPresentId(present.getId());
        redPacketVo.setPresentType(present.getTypeid());
        redPacketVo.setRoomId(roomId);
        redPacketVo.setPresentUrl(present.getShowpic());
        redPacketVo.setBeforeFanpiao(balance);
        redPacketVo.setZhuboId(zhuboId);
        redPacketVo.setExp(present.getExperience());

        String onsEnv = DynamicProperties.getString("ons.env");
        // 给队列发消息，完成后续工作
        Message message = new Message();
        message.setTag(onsEnv);
        message.put("redPacketVo", JSON.toJSONString(redPacketVo));
        message.setTopic(TopicRegistry.HEFANTV_RED);
        onsProducer.sendMsg(message);

        RebalanceVo rebalanceVo = new RebalanceVo();
        rebalanceVo.setLiveUuid(redPacketVo.getLiveUuid());
        rebalanceVo.setFromId(redPacketVo.getUserId());
        rebalanceVo.setToId(redPacketVo.getZhuboId());
        rebalanceVo.setPresentId(redPacketVo.getPresentId());
        rebalanceVo.setSource(GlobalConstants.SOURCE_TYPE_LIVE);
        rebalanceVo.setPrice(present.getPrice());
        rebalanceVo.setIsFalse(GlobalConstants.REAL_FANPIAO);
        rebalanceVo.setPresentName(present.getPresentName());
        rebalanceVo.setPresentNum(1);
        rebalanceVo.setBeforeFanpiao(balance);
        rebalanceVo.setUniqueKey("");
        Message messageOrder = new Message();
        messageOrder.setTag(onsEnv);
        messageOrder.put("rebalanceVoOrder", JSON.toJSONString(rebalanceVo));
        messageOrder.setTopic(TopicRegistry.HEFAN_ORDER);
        onsProducer.sendMsg(messageOrder);

      } else {
        return new ResultBean(ResultCode.UNSUCCESS.get_code(), "礼物基础信息有误");
      }
    } catch (Exception e) {
      e.printStackTrace();
      logger.error(e.getMessage());
    }

    return new ResultBean(ResultCode.SUCCESS.get_code(), ResultCode.SUCCESS.getMsg());
  }

  @RequestMapping(value = "/grapRedPacket", method = RequestMethod.GET)
  @ResponseBody
  public ResultBean grapRedPacket(HttpServletRequest request) {

    Map m = HttpUtils.initParam(request, Map.class);
    if (CollectionUtils.isEmpty(m)) {
      return new ResultBean(ResultCode.ParamException.get_code(), "参数错误");
    }
    String userId = MapUtils.getStrValue(m, "userId", "");
    long redOrderId = MapUtils.getLongValue(m, "redId", 0);
    String nickName = MapUtils.getStrValue(m, "nickName", "");
    if (StringUtils.isBlank(userId) || redOrderId <= 0 || StringUtils.isBlank(nickName)) {
      return new ResultBean(ResultCode.ParamException.get_code(), "参数验证错误");
    }
    WebUser user = webUserService.getWebUserInfoByUserId(userId);
    if (user == null) {
      return new ResultBean(ResultCode.ParamException.get_code(), "参数验证错误");
    }
    OrderRedPacket order = redPacketService.getOrderPacketbyId(redOrderId);
    //红包不存在
    if (order == null) {
      return new ResultBean(ResultCode.ParamException.get_code(), "参数验证错误");
    }
    //不能抢自己红包
    if (user.getUserId().equals(order.getUserId())) {
      return new ResultBean(ResultCode.ParamException.get_code(), "自己不能抢自己发的红包");
    }
    if (user.getUserType() == GlobalConstants.USER_TYPE_FLASE) {
      return new ResultBean(ResultCode.UNSUCCESS.get_code(), "虚拟币用户无法发红包");
    }
    //是否已经抢过本次红包
    boolean isHaving = redPacketService.isGrabRedPack(redOrderId, userId);
    if (isHaving) {
      return new ResultBean(ResultCode.ParamException.get_code(), "用户不能重复抢红包");
    }

    Map<String, Object> resultMap = Maps.newHashMap();
    boolean iswin = false;
    try {
      String pkey = String.format(RedisKeyConstant.RED_PACKET_PEOPLE_KEY, redOrderId);
      String people = jedisService.getStr(pkey);
      List<String> list = JSON.parseArray(people, String.class);
      logger.info("红包DetailId={},中奖名单如下={}", redOrderId, people);
      if (!CollectionUtils.isEmpty(list)) {
        for (String p : list) {
          if (p.equals("{\"userId\":\"" + userId + "\"}")) {
            iswin = true;
            break;
          }
        }

      }

      resultMap.put("iswin", "0");
      resultMap.put("value", "0");
      if (iswin) {
        String mkey = String.format(RedisKeyConstant.RED_PACKET_MONEY_KEY, redOrderId);
        //随机金额
        String value = jedisService.spop(mkey);
        if (value != null) {

          OrderRedPacketDetail orderRedPacketDetail = JSON.parseObject(value, OrderRedPacketDetail.class);
          RedPackQiangVo redPackQiangVo = new RedPackQiangVo();
          redPackQiangVo.setOrderId(redOrderId);
          redPackQiangVo.setDetailId(orderRedPacketDetail.getId());
          redPackQiangVo.setFanpiaoNum(orderRedPacketDetail.getFanpiaoNum());
          redPackQiangVo.setUserId(userId);
          redPackQiangVo.setNickName(nickName);
          // 给队列发消息，完成后续工作
          String onsEnv = DynamicProperties.getString("ons.env");
          Message message = new Message();
          message.setTag(onsEnv);
          message.put("redPackQiangVo", JSON.toJSONString(redPackQiangVo));
          message.setTopic(TopicRegistry.HEFANTV_REDQ);
          onsProducer.sendMsg(message);

          resultMap.put("iswin", "1");
          resultMap.put("value", orderRedPacketDetail.getFanpiaoNum());
        }
      }

    } catch (Exception e) {
      logger.error("用户{}抢红包{}异常{}", userId, redOrderId, e.getMessage());
      //不管是啥异常，都没抢到
      resultMap.put("iswin", "0");
      resultMap.put("value", "0");
    }

    return new ResultBean(ResultCode.SUCCESS.get_code(), ResultCode.SUCCESS.getMsg(), resultMap);
  }

}
